#include <linux/module.h>
#include <asm/uaccess.h>
#include <linux/fs.h>

#define CONFIG_FILE	"/home/yt/tn/kmod/07_read_write_vfs/test.cfg"

struct file *filp;

static int __init hello_init(void)
{
	int ret = 0;
	char buf[64];
	mm_segment_t fs_flag;

	filp = filp_open(CONFIG_FILE, O_RDWR | O_CREAT, 0664);
	if (IS_ERR(filp)) {
		printk("%s: Can not open the config file.\n", __FUNCTION__);
		ret = -EFAULT;
		goto err_1;
	}

	fs_flag = get_fs();
	set_fs(KERNEL_DS);

	vfs_llseek(filp, 11, SEEK_SET);

	memset(buf, 0, 64);
	ret = vfs_read(filp, buf, 3, &filp->f_pos);
	if (ret < 0) {
		printk("%s: VFS Read error.\n", __FUNCTION__);
		goto err_2;
	}

	printk("Get: %s\n", buf);

	ret = vfs_write(filp, "fuck", 4, &filp->f_pos);
	if (ret < 0) {
		printk("%s: VFS Write error.\n", __FUNCTION__);
		goto err_2;
	}

	ret = 0;
err_2:
	set_fs(fs_flag);
	filp_close(filp, NULL);
err_1:
	return ret;
}

static void __exit hello_exit(void)
{
}

module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("YYW");
